import {AxiosError} from 'axios'
import {JsonRespBase} from '../../lib/defs/comm'
import {ErrorObject} from '@vuelidate/core'

export const getAxiosErrMsg = function (err: any): string {
  if (!err) {
    return ''
  }
  const axiosError = err as AxiosError
  const jsonRespBase = axiosError.response?.data as JsonRespBase
  if (jsonRespBase?.msg) {
    return jsonRespBase.msg
  }
  const error = err as Error
  return error.message
}

export const getAxiosErrCode = function (err: any): number | null {
  if (!err) {
    return null
  }
  const axiosError = err as AxiosError
  return axiosError.response?.status ?? null
}

export const getAxiosErrIcon = function (err: any) {
  const errCode = getAxiosErrCode(err)
  if (errCode && errCode < 500) {
    return 'ReqErr'
  }
  return 'Error'
}

export const getFieldErrStr = function (errors: ErrorObject[]): string | undefined {
  if (errors.length) {
    if (typeof errors[0].$message === 'string') {
      return errors[0].$message
    } else {
      return errors[0].$message.value
    }
  }
  return undefined
}
